package com.rtsapp.server.network.protocol.crypto;

import com.rtsapp.server.logger.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

/**
 * RC4加密输出流
 */
public class RC4OutHandler extends ChannelOutboundHandlerAdapter {

    private static final Logger LOGGER = com.rtsapp.server.logger.LoggerFactory.getLogger(RC4OutHandler.class);

    private final RC4 rc4;

    public RC4OutHandler(byte[] crpytKey) {
        rc4 = new RC4(crpytKey);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

        if (msg instanceof ByteBuf) {
            ByteBuf buffer = (ByteBuf) msg;
            if (buffer.isReadable()) {
                rc4.crypt0(buffer, buffer.readerIndex(), buffer.writerIndex());
            }
            ctx.write( buffer, promise );
        } else {
            LOGGER.error("RC4OutHandler 不能编码ByteBuf之外的内容");
        }
    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);

        //TODO 通道移除的时候，可以将RC4中的byte数组回收
    }

}
